package com.ajhlp.spring_modules.html;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.util.Assert;

public class HtmlDocumentHandler {
	
	private Document document;
	
	private File source;
	
	private String sourceFileEncode;
	
	/**
	 * 获得Document对象
	 * @return
	 */
	public Document getDocument() {
		return document;
	}

	public HtmlDocumentHandler(Document document){
		Assert.notNull(document,"document must not null");
		
		this.document = document;
		
	}
	
	public HtmlDocumentHandler(File file, String encode){
		Assert.notNull(file,"file must not null");
		Assert.notNull(encode,"encode must not null");
		
		this.document = HtmlDocumentFactory.getDocument(file, encode);
		
		Assert.notNull(document,"document read error");
		
		this.source = file;
		this.sourceFileEncode = encode;
		
	}
	
	/**
	 * 获取节点
	 * @param query 查询表达式
	 * @return
	 */
	public Elements selectNodes(String query){
		return this.getDocument().select(query);
	}
	
	/**
	 * 保存至原文件
	 * @throws IOException
	 */
	public void save() throws IOException{
		Assert.notNull(source, "source file must init first");
		Assert.notNull(sourceFileEncode,"source file charset must init first");
		
		FileUtils.write(source, this.getDocument().toString(), sourceFileEncode, false);
	}
	
	/**
	 * 保存到目标文件
	 * @param target
	 * @param encode
	 * @param append
	 * @throws IOException
	 */
	public void save(File target,String encode,boolean append) throws IOException{
		FileUtils.write(target, this.getDocument().toString(), encode, append);
	}
	
}
